<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3>{{$t('report.staffCategoryChart.title1')}}
        <el-popover trigger="hover" v-if="type !== 'profit-event'">
          <ul>
            <li>{{ $t('report.staffCategoryChart.title11') }}</li>
            <li>{{ $t('report.staffCategoryChart.title12') }}</li>
            <li>{{ $t('report.staffCategoryChart.title14') }}</li>
            <li> {{ $t('report.staffCategoryChart.title4') }}</li>
            <li>
              <div>{{$t('report.staffCategoryChart.title18')}}</div>
              <div>{{$t('report.staffCategoryChart.title15')}}</div>
              <div>{{$t('report.staffCategoryChart.title16')}}</div>
              <div>{{$t('report.staffCategoryChart.title17')}}</div>
            </li>
          </ul>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>

        <el-popover trigger="hover" v-else>
          {{ $t('report.staffCategoryChart.title14') }}
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
      <div class="stats-form-groups">
        <div class="stats-form-group stats-checkbox task-mr12">
          <base-checkbox :value="ignoreDeleted" @input="chooseCategoryDeleted">{{$t('report.staffEventTable.title2')}}</base-checkbox>
        </div>
        <div class="stats-form-group stats-checkbox task-mr12">
          <base-checkbox :value="categoryIgnoreNull" @input="chooseCategoryIgnore">{{$t('report.staffCategoryChart.text2')}}</base-checkbox>
        </div>
        <div v-if="categoryType == $t('report.eventScoreChart.label3') || type == 'profit-event'">
          {{ $t('report.staffTaskTable.label2') }}:
            <el-select :value="state" @input="chooseTaskStatus" :placeholder="$t('report.staffTaskTable.placeholder1')">
              <el-option
                v-for="item in taskStatusOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </div>
        <biz-team-select multiple is-auto-select-child collapse class="stats-team-select biz-team-select task-mb2" :value="tag" @input="chooseCategoryTeam" :fetch-func="fetchTeam" @remove="clearTeam"/>

        <div class="stats-form-group">
          <date-picker @datePicker="datePicker" />
        </div>
      </div>
    </div>
    <div class="stats-panel-body">
      <div style="text-align: center;" v-if="type !== 'profit-event'">
        <div class="stats-btn-group">
          <button
            v-for="btn in btnOptions"
            :key="btn.value"
            type="button"
            :class="{'stats-checked': categoryType == btn.value}"
            @click="chooseCategoryType(btn.value)">
            {{ btn.name }}
          </button>
        </div>
      </div>
      <div class="category-chart-wrap">
        <div id="category"></div>
        <stats-chart-empty v-if="categoryEmpty">{{$t('common.base.tip.noData')}}</stats-chart-empty>
      </div>
      <div class="stats-staff-category-wrap" v-if="showTable">
        <div class="stats-table-header">
          <h3>{{$t('common.label.taskList')}}</h3>

          <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button>          
          <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
        </div>
        <div>
          <el-table :data="page.list" class="stats-table">
            <el-table-column :label="$t('common.base.serialNumber')" prop="taskNo" width="150px" :show-overflow-tooltip="false">
              <template slot-scope="scope">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip :content="scope.row.taskNo" placement="top" :disabled="!isContentTooltip">
                      <a href="#" @click="openDetail(scope.row)">{{scope.row.taskNo}}</a>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.label.taskTemplate')" prop="templateName" width="120px"></el-table-column>
            <el-table-column :label="$t('common.base.customer')" prop="customer.name" min-width="240px"></el-table-column>
            <el-table-column :label="`${$t('report.customer.label5')} (${$t('common.base.yuan')})`" prop="profit" width="200px" v-if="categoryType == $t('report.eventScoreChart.label3')">
              <template slot-scope="scope">
                <span>{{ scope.row.profit.toFixed(2) }}</span>
              </template>
            </el-table-column>

            <template v-if="categoryType == $t('common.base.degree')">
              <el-table-column :label="$t('common.base.degree')" prop="degree" width="100px"></el-table-column>
              <div v-if="notShowSatisfied">
                <template v-if="hasStar">
                  <el-table-column v-for="(field, index) in evaluateConfig.starEvaluates" :label="field" :prop="`evaluateObj.${evaluateConfig.starEvaluateFeilds[index]}`" :key="field"/>
                </template>
                <el-table-column :label="$t('report.eventScoreChart.label1')" width="200px" prop="evaluateObj.tagEvaluates" show-overflow-tooltip v-if="hasTag">
                  <template slot-scope="scope">{{scope.row.evaluateObj && scope.row.evaluateObj.tagEvaluates | prettyArray}}</template>
                </el-table-column>
                <el-table-column :label="$t('common.label.customerEvaluation')" width="240px" prop="evaluateContent" show-overflow-tooltip></el-table-column>
              </div>
              <el-table-column :label="$t('report.eventScoreChart.label2')" width="240px" prop="suggestion" show-overflow-tooltip></el-table-column>
            </template>    
              
            <template v-if="categoryType == $t('report.staffCategoryChart.title9')">
              <el-table-column :label="$t('task.detail.components.acceptTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.acceptUsedTime)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('task.detail.components.taskTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.taskUsedTime)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('task.detail.components.workTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.workUsedTime)}}
                </template>
              </el-table-column>
            </template>
            <el-table-column :label="$t('common.base.status')" prop="state" width="100px">
              <template slot-scope="scope">
                {{scope.row.state | taskStateName}}
              </template>
            </el-table-column>
            
            <el-table-column :label="$t('common.fields.executorUser.displayName')" width="120px">
              <template v-if="scope.row.executor" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.executor.staffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.executor.displayName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.base.createUser')" width="120px">
              <template v-if="scope.row.createUser" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.createUser.staffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.createUser.displayName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.base.column.createTime')" width="180px">
              <template slot-scope="scope">
                {{scope.row.createTime | fmt}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.label.finishTime')" width="180px">
              <template slot-scope="scope">
                {{scope.row.completeTime | fmt}}
              </template>
            </el-table-column>
          </el-table>

          <el-pagination class="stats-pagination"
                         background @current-change="jump"
                         :current-page="page.pageNum"
                         layout="total, prev, pager, next"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { t } from '@src/locales';
import { isOpenData, openAccurateTab } from '@src/util/platform';
/* global AMap, moment, _init_data*/
import _ from 'lodash';
import http from 'src/util/HttpUtil';
import qs from 'src/util/querystring';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import echarts from 'packages/Echarts';

import Loading from 'packages/BaseLoading';
import BaseCheckbox from 'packages/BaseCheckbox.vue';
import SampleTooltip from 'packages/SampleTooltip'
import { isBasicEditionHidePay, isEnterpriseEdition } from '@shb-lib/version';
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
import { getThemeColor } from '@src/util/business/color'

import { useNewVue } from '@hooks/useNewVue'
const { createVue } = useNewVue();

const USER_TASK_LEGEND = [t('common.base.add'), t('common.base.finish')];
const USER_TASK_OBJ = { [t('common.base.add')]: 'taskCount', [t('common.base.finish')]: 'finishedTask' }
const USER_TASK_COLOR = ['#6da9e7', '#48e8ab'];

const USER_EXPENSE_LEGEND = [t('report.staffCategoryChart.title10')];
const USER_EXPENSE_OBJ = { [t('report.staffCategoryChart.title10')]: 'receivables' }
const USER_EXPENSE_COLOR = ['#48e8ab'];

const USER_DEGREE_LEGEND = [ t('common.base.satisfactionDegree.0'), t('common.base.satisfactionDegree.1'),t('common.base.satisfactionDegree.2'),t('common.base.satisfactionDegree.3'),t('common.base.satisfactionDegree.4')];
const USER_DEGREE_OBJ = { [t('common.base.satisfactionDegree.1')]: 'satisfication', [t('common.base.satisfactionDegree.0')]: 'verySatifaction', [t('common.base.satisfactionDegree.2')]: 'general', [t('common.base.satisfactionDegree.3')]: 'unSatisfication', [t('common.base.satisfactionDegree.4')]: 'veryUnSatifaction'}
const USER_DEGREE_COLOR = [ getThemeColor(),'#48e8ab', '#6da9e7', '#ffdd92', '#f6903d'];

const USER_EFFICIENCY_LEGEND = [t('report.common.averageTime.3'), t('report.common.averageTime.4'), t('report.common.averageTime.1')];
const USER_EFFICIENCY_OBJ =  { [t('report.common.averageTime.3')]: 'AverageAcceptUsedTime', [t('report.common.averageTime.4')]: 'AverageTaskUsedTime', [t('report.common.averageTime.1')]: 'AverageWorkUsedTime' }
const USER_EFFICIENCY_COLOR = ['#48e8ab', '#6da9e7', '#ffdd92'];

let category = null;

export default {
  name: 'staff-category-chart',
  props: {
    type: {
      type: String,
      default: ''
    },
    evaluateConfig: {
      type: Object || Array
    }
  },
  data(){
    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      tag: [],
      sort: '',
      // value对应categoryType，是中文，国际化需要留意下~
      btnOptions: [{
        value: t('common.base.task'),
        name: t('common.base.task'),
        trackLabel: 'TASK', // 导出埋点用
      }, {
        value: t('report.eventScoreChart.label3'),
        name: t('report.eventScoreChart.label3'),
        trackLabel: 'REVENUE',
      }, {
        value: t('common.base.degree'),
        name: t('common.base.degree'),
        trackLabel: 'SATISFACTION',
      }, {
        value: t('report.staffCategoryChart.title9'),
        name: t('report.staffCategoryChart.title9'),
        trackLabel: 'EFFICIENCY',
      }],
      categoryType: t('common.base.task'),
      categoryData: {},
      categoryIgnoreNull: true,
      categoryStartTime: '',
      categoryEndTime: '',
      categoryTeamId: '',
      categoryEmpty: false,

      showTable: false,
      model: {
        pageNum: 1,
        userId: '',
        selectType: ''
      },
      page: {},
      taskStatusOption: [{
        value: 'finished',
        label: t('report.common.taskState.0')
      }, {
        value: 'costed',
        label: t('report.common.taskState.2')
      }],
      state: 'finished',
      ignoreDeleted: true
    }
  },
  computed: {
    notShowSatisfied() {
      const RootWindow = getRootWindow(window);
      return !(isEnterpriseEdition()) && !(RootWindow?.grayAuth?.satisfaction)
    },
    hasStar(){
      return this.evaluateConfig.useStarEvaluate;
    },
    hasTag(){
      return this.evaluateConfig.useTagEvaluate;
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    }
  },
  methods: {
    clearTeam(value = []){
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.categoryTeamId = ids.join(',');
      this.renderCategory();
    },
    chooseTaskStatus(value) {
      this.state = value
      this.renderCategory();
      // 选择统计来源埋点
      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_TASK_STATUS_FILTER', this.$track)
    },
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    exportAllData(){
      let model = {
        tagId: this.categoryTeamId,
        timeStart: `${this.categoryStartTime }`,
        timeEnd: `${this.categoryEndTime }`,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted
      };
      if(this.categoryType == t('report.eventScoreChart.label3') || this.type == 'profit-event') {
        model.state = this.state
      }
      let selectType = 'task';
      if(this.categoryType == t('report.eventScoreChart.label3')) selectType = 'expense';
      if(this.categoryType == t('common.base.degree')) selectType = 'degree';
      if(this.categoryType == t('report.staffCategoryChart.title9')) selectType = 'time';

      model.selectType = selectType;
      window.location.href = `/api/report/outside/stats/executorTask/exportAll?${ qs.stringify(model)}`;

      this.exportTrack(true)
    },
    exportData(){
      let model = {
        tagId: this.categoryTeamId,
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        userId: this.model.userId,
        selectType: this.model.selectType,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted
      };
      if(this.categoryType == t('report.eventScoreChart.label3') || this.type == 'profit-event') {
        model.state = this.state
      }
      window.location.href = `/api/report/outside/stats/executorTask/export?${ qs.stringify(model)}`;

      this.exportTrack(false)
    },
    exportTrack(isExportAll) {
      const tab = this.btnOptions.find(v => v.value === this.categoryType).trackLabel;
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.type,
        tab
      }, '*')
    },
    openDetail(row){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `taskView_${ row.id}`, 
      //   title: `工单${row.taskNo}`,
      //   close: true, 
      //   url: `/task/view/${row.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: row.id,
        titleKey: row.taskNo,
        fromId
      })
    },
    fetchTableData(){
      let model = {
        tagId: this.categoryTeamId,
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        userId: this.model.userId,
        selectType: this.model.selectType,
        pageNum: this.model.pageNum
      };
      if(this.categoryType == t('report.eventScoreChart.label3') || this.type == 'profit-event') {
        model.state = this.state
      }
      return http.post('/api/report/outside/stats/staff/taskList', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);

      try {
        this.page = await this.fetchTableData();
        this.showTable = true;
      } catch (error) {
        console.log(error);
      }

      instance.hide();
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    // 时间赋值
    initDate(start, end){
      this.categoryStartTime = start;
      this.categoryEndTime = end;
      this.renderCategory();
    },
    // 初始化图表
    initCategory(){
      category = echarts.init(document.getElementById('category'));
      category.on('click', event => {
        let seriesName = event.seriesName;
        let origin = event.data._origin;
                
        let selectType = 'taskAdd';
        if(seriesName == t('common.base.finish')) selectType = 'taskFinish'
        if(seriesName == t('report.staffCategoryChart.title10')) selectType = 'expense'
        if(seriesName == t('common.base.satisfactionDegree.0')) selectType = 'degreeVerySatifaction';
        if(seriesName == t('common.base.satisfactionDegree.1')) selectType = 'degreeSatifaction'
        if(seriesName == t('common.base.satisfactionDegree.2')) selectType = 'degreeGeneral'
        if(seriesName == t('common.base.satisfactionDegree.3')) selectType = 'degreeUnsatifaction';
        if(seriesName == t('common.base.satisfactionDegree.4')) selectType = 'degreeVeryUnSatifaction';
        if(seriesName == t('report.common.averageTime.3')) selectType = 'acceptTime';
        if(seriesName == t('report.common.averageTime.4')) selectType = 'taskTime';
        if(seriesName == t('report.common.averageTime.1')) selectType = 'workTime';

        this.model.pageNum = 1;
        this.model.userId = origin.userId;
        this.model.selectType = selectType;

        this.renderTable()
      })
      category.on('legendselectchanged', event => {
        let arr = [];
        let opt = category.getOption();
        for(let [key, value] of Object.entries(event.selected)) {
          arr.push({key, value});
        }
        arr.some(item => {
          if(item.value) {
            this.sort = item.key;
            return true;
          }
        })

        if(this.categoryType == t('common.base.task')) {
          let sort = this.sortTaskTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('common.base.degree')) {
          let sort = this.sortDegreeTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('report.staffCategoryChart.title9')) {
          let sort = this.sortEfficiencyTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        }

        category.setOption(opt);
      })
    },
    chooseCategoryIgnore(value){
      this.categoryIgnoreNull = value;
      this.renderCategory();
    },
    chooseCategoryDeleted(value) {
      this.ignoreDeleted = value;
      this.renderCategory();
    },
    chooseCategoryDate(start, end){
      this.$emit('trackEvent', 'chooseDate');

      this.categoryStartTime = start;
      this.categoryEndTime = end;
      this.renderCategory();
    },
    chooseCategoryTeam(value){
      this.$emit('trackEvent', 'chooseTeam');
      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      this.tag = value;
      // this.categoryTeamId = tag.id;
      
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.categoryTeamId = ids.join(',');

      this.renderCategory();
      // 部门埋点
      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TEAM', this.$track)
    },
    async renderCategory(event){
      try {
        let instance = Loading.show(this.$el);
        this.categoryData = await this.fetchCategoryData();

        instance.hide();
        this.showTable = false;
      
        if (this.type === 'profit-event') {
          this.categoryType = t('report.eventScoreChart.label3')
        } else {
          this.categoryType = t('common.base.task');
        }
        this.setCategoryOption(event);
      } catch (error) {
        console.log(error)
      }
    },
    chooseCategoryType(type){
      this.$emit('trackEvent', type);

      this.categoryType = type;
      this.setCategoryOption();
    },
    setCategoryOption(event){
      this.categoryEmpty = false;
      category && category.clear();

      let option = null;
      if(this.categoryType == t('common.base.task')){
        let taskOption = this.getCategoryTaskOption();
        if(taskOption) option = this.getCategoryOption(taskOption);
      }

      if(this.categoryType == t('report.eventScoreChart.label3')){
        let expenceOption = this.getCategoryExpenceOption()
        if(expenceOption) option = this.getCategoryOption(expenceOption);
      }

      if(this.categoryType == t('common.base.degree')){
        let degreeOption = this.getCategoryDegreeOption();
        if(degreeOption) option = this.getCategoryOption(degreeOption);
      }

      if(this.categoryType == t('report.staffCategoryChart.title9')){
        let efficiencyOption = this.getCategoryEfficiencyOption()
        if(efficiencyOption) option = this.getCategoryOption(efficiencyOption);
      }
      
      if(null == option){
        this.categoryEmpty = true;
        return
      }

      category && category.setOption(option);
    },
    async handleStaffData(res, type){
      if(!res[type] || !res[type].length) return res
      let originItems = res[type].filter(item=>item.displayName)
      let items = originItems.map(item => {
        return {
          type: 'userName',
          id: item.staffId
        }
      })

      const result = await new Promise((resolve, reject) => {
        window.WWOpenData.prefetch({ items }, (err, data) => {
          if (err) {
            return reject(err)
          }
          resolve(data)
        })
      })
      
      try {
        res[type] = originItems.map((item, index) => {
          return Object.assign(item, { displayName: result.items[index].data })
        })
      } catch (error) {
        console.warn(error)
      }

      return res
    },
    fetchCategoryData(){
      let params = {
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        tagId: this.categoryTeamId,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted
      };
      if(this.categoryType == t('report.eventScoreChart.label3') || this.type == 'profit-event') {
        params.state = this.state
      }
      return http.post('/api/dataware/outside/staffStatistics/pcStaffData', params).then(async res=>{
        if(res.code !== 200) return res.msg
        if (this.isOpenData) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
         
          let allHandleStaffDataPromise = Object.keys(res).map(item =>{
            return this.handleStaffData(res.data, item)
          })
          
          await Promise.all(allHandleStaffDataPromise) 
        }

        return res.data
      })
    },
    getCategoryEfficiencyOption(){
      let ctx = this;
      let data = this.categoryData.efficiency || [];

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = []; // 平均接单用时
      let atuTime = []; // 平均工单用时
      let awuTime = []; // 平均工作用时

      let maxData = 0;
      data.sort((prev, next) => prev.AverageAcceptUsedTime - next.AverageAcceptUsedTime);
      data.forEach(item => {
        yAxisData.push(item.displayName);

        aauTime.push({
          value: item.AverageAcceptUsedTime, 
          _origin: item
        });

        atuTime.push({
          value: item.AverageTaskUsedTime,
          _origin: item
        });

        awuTime.push({
          value: item.AverageWorkUsedTime,
          _origin: item
        });

        if(item.AverageAcceptUsedTime >= maxData) maxData = item.AverageAcceptUsedTime;
        if(item.AverageTaskUsedTime >= maxData) maxData = item.AverageTaskUsedTime;
        if(item.AverageWorkUsedTime >= maxData) maxData = item.AverageWorkUsedTime;
      });

      series.push({
        name: USER_EFFICIENCY_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: aauTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: atuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        data: awuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      let interval = this.computeInterval(maxData);

      let option = {
        title: t('report.statistics.title6'),
        legend: USER_EFFICIENCY_LEGEND,
        color: USER_EFFICIENCY_COLOR,
        tooltip: {
          formatter(data){
            let html = '';
            if(ctx.isOpenData) {
              let staffId = data[0].data._origin.staffId
              let id = Math.ceil(Math.random() * 1000)
              html = `<ww-open-data type="userName" openid="${staffId}" id="wwOpenData${id}"></ww-open-data>`
              setTimeout(() => {
                window.WWOpenData && window.WWOpenData.bind(document.getElementById(`wwOpenData${id}`))
              }, 500);
            }else {
              let name = data[0].name;
              html += `<div>${name}</div>`;
            }

            data.forEach(item => {
              html += `<div>${item.marker} ${item.seriesName}: ${ctx.formatterTime(item.value >> 0)}</div>`;
            })

            return html;
          }
        },
        xAxis: {
          axisLabel: {
            show: true,
            formatter (value, index) {
              let temp = ctx.formatterTime(value >> 0);
              return temp == '--' ? 0 : temp;
            }
          }
        },
        yAxisData,
        series
      }

      if(interval.min != null) option.xAxis.minInterval = interval.min;
      if(interval.max != null) option.xAxis.maxInterval = interval.max;

      return option;
    },
    sortEfficiencyTable () {
      let data = this.categoryData.efficiency || [];

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = []; // 平均接单用时
      let atuTime = []; // 平均工单用时
      let awuTime = []; // 平均工作用时

      let maxData = 0;

      if(this.sort == t('report.common.averageTime.3')) {
        data.sort((prev, next) => prev.AverageAcceptUsedTime - next.AverageAcceptUsedTime);
      } else if(this.sort == t('report.common.averageTime.4')) {
        data.sort((prev, next) => prev.AverageTaskUsedTime - next.AverageTaskUsedTime);
      } else {
        data.sort((prev, next) => prev.AverageWorkUsedTime - next.AverageWorkUsedTime);
      }
      data.forEach(item => {
        yAxisData.push(item.displayName);

        aauTime.push({
          value: item.AverageAcceptUsedTime, 
          _origin: item
        });

        atuTime.push({
          value: item.AverageTaskUsedTime,
          _origin: item
        });

        awuTime.push({
          value: item.AverageWorkUsedTime,
          _origin: item
        });

        if(item.AverageAcceptUsedTime >= maxData) maxData = item.AverageAcceptUsedTime;
        if(item.AverageTaskUsedTime >= maxData) maxData = item.AverageTaskUsedTime;
        if(item.AverageWorkUsedTime >= maxData) maxData = item.AverageWorkUsedTime;
      });

      series.push({
        name: USER_EFFICIENCY_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: aauTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: atuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        data: awuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        series,
        yAxisData
      }
    },
    getCategoryTaskOption(){
      let data = this.categoryData.taskCount || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let createdData = [];
      let finishedDate = [];
      let series = [];
      
      data.sort((prev, next) => prev.taskCount - next.taskCount).forEach(item => {
        yAxisData.push(item.displayName);
        createdData.push({
          value: item.taskCount,
          _origin: item
        });
        finishedDate.push({
          value: item.finishedTask,
          _origin: item
        });
      });
      
      series.push({
        name: USER_TASK_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_TASK_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedDate,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.statistics.title11'),
        legend: USER_TASK_LEGEND,
        color: USER_TASK_COLOR,
        yAxisData,
        series
      }
    },
    sortTaskTable () {
      let data = this.categoryData.taskCount || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let createdData = [];
      let finishedDate = [];
      let series = [];
      
      if(this.sort == t('common.base.finish')) {
        data.sort((prev, next) => prev.finishedTask - next.finishedTask);
      } else {
        data.sort((prev, next) => prev.taskCount - next.taskCount);
      }
      data.forEach(item => {
        yAxisData.push(item.displayName);
        createdData.push({
          value: item.taskCount,
          _origin: item
        });
        finishedDate.push({
          value: item.finishedTask,
          _origin: item
        });
      });

      series.push({
        name: USER_TASK_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_TASK_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedDate,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        series,
        yAxisData
      }
    },
    getCategoryExpenceOption(){
      let data = this.categoryData.expense || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let expenseData = [];
      let series = [];

      data.sort((prev, next) => prev.receivables - next.receivables).forEach(item => {
        yAxisData.push({
          value: item.displayName,
          _origin: item
        });
        expenseData.push({
          value: item.receivables,
          _origin: item
        });
      });

      series.push({
        name: USER_EXPENSE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: expenseData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.statistics.title10'),
        legend: USER_EXPENSE_LEGEND,
        color: USER_EXPENSE_COLOR,
        yAxisData,
        series
      }
    },
    getCategoryDegreeOption(){
      let series = [];
      let data = this.categoryData.degree || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let satisData = [];// 满意
      let verySatisData = [] // 非常满意
      let generaldData = [];// 一般
      let unsatisData = []; // 不满意
      let veryUnSatisData = [] // 非常不满意

      data.sort((prev, next) => prev.satisfication - next.satisfication).forEach(item => {
        yAxisData.push(item.displayName);
        verySatisData.push({
          value: item.verySatifaction,
          _origin: item
        });
        satisData.push({
          value: item.satisfication,
          _origin: item
        });
        generaldData.push({
          value: item.general,
          _origin: item
        });
        unsatisData.push({
          value: item.unSatisfication,
          _origin: item
        });
        veryUnSatisData.push({
          value: item.veryUnSatifaction,
          _origin: item
        });
      });

      series.push({
        name: USER_DEGREE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: verySatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[3],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: unsatisData,
        itemStyle : { normal: {label : {show: true}}}
      })
      series.push({
        name: USER_DEGREE_LEGEND[4],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: veryUnSatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.statistics.title8'),
        legend: USER_DEGREE_LEGEND,
        color: USER_DEGREE_COLOR,
        yAxisData,
        series
      };
    },
    sortDegreeTable () {
      let series = [];
      let data = this.categoryData.degree || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let verySatisData = [] // 非常满意
      let satisData = [];// 满意
      let generaldData = [];// 一般
      let unsatisData = []; // 不满意
      let veryUnSatisData = [] // 非常不满意

      if(this.sort == t('common.base.satisfactionDegree.4')) {
        data.sort((prev, next) => prev.verySatifaction - next.verySatifaction);
      } else if(this.sort == t('common.base.satisfactionDegree.1')) {
        data.sort((prev, next) => prev.satisfication - next.satisfication);
      } else if(this.sort == t('common.base.satisfactionDegree.2')) {
        data.sort((prev, next) => prev.general - next.general);
      } else if(this.sort == t('common.base.satisfactionDegree.4')){
        data.sort((prev, next) => prev.unSatisfication - next.unSatisfication);
      }else{
        data.sort((prev, next) => prev.veryUnSatifaction - next.veryUnSatifaction);
      }

      data.forEach(item => {
        yAxisData.push(item.displayName);
        verySatisData.push({
          value: item.verySatifaction,
          _origin: item
        });
        satisData.push({
          value: item.satisfication,
          _origin: item
        });
        generaldData.push({
          value: item.general,
          _origin: item
        });
        unsatisData.push({
          value: item.unSatisfication,
          _origin: item
        });
        veryUnSatisData.push({
          value: item.veryUnSatifaction,
          _origin: item
        });
      });

      series.push({
        name: USER_DEGREE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: verySatisData,
        itemStyle : { normal: {label : {show: true}}}
      })
      series.push({
        name: USER_DEGREE_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[3],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: unsatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[4],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: veryUnSatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        yAxisData,
        series
      };
    },
    getCategoryOption(option){
      let that = this
      let originObj = {}
      let originColor = []
      if(this.categoryType == t('common.base.task')) {
        originObj = USER_TASK_OBJ
        originColor = USER_TASK_COLOR
      }else if(this.categoryType == t('report.eventScoreChart.label3')){
        originObj = USER_EXPENSE_OBJ
        originColor = USER_EXPENSE_COLOR
      }else if(this.categoryType == t('common.base.degree')){
        originObj = USER_DEGREE_OBJ
        originColor = USER_DEGREE_COLOR
      }else if(this.categoryType == t('report.staffCategoryChart.title9')){
        originObj = USER_EFFICIENCY_OBJ
        originColor = USER_EFFICIENCY_COLOR
      }
      let yAxisData = option.yAxisData;

      let start = 0;
      let end = yAxisData.length - 1;
      if(yAxisData.length > 10) start = end - 9;

      let _option = {
        color: option.color,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            let staffId = params[0].data._origin.staffId
            let executorName = params[0].name
            let id = Math.ceil(Math.random() * 1000)

            let element = `<div id="echart-item_${id}"></div>`
            that.$nextTick(()=>{
              createVue({
                el:`#echart-item_${id}`,
                components: {
                  // [OpenDataComponent.name]: OpenDataComponent
                  'test-component': {
                    render(h) {
                      return h(
                        'div', null, [
                          isOpenData ? h('open-data', {
                            props:{
                              type:'userName',
                              openid:staffId
                            }
                          }) : null,
                          !isOpenData ? h('div', null, executorName) : null,
                          option.legend.length > 0 ?  option.legend.map((item, index) => {
                            return h('div', null, [
                              h('span', 
                                {
                                  style: {
                                    display: 'inline-block',
                                    width: '12px',
                                    height: '12px',
                                    backgroundColor: originColor[index],
                                    borderRadius: '50%',
                                    marginRight:'5px'
                                  }
                                }
                              ),
                              h('span', `${item}: ${params[0].data._origin[originObj[item]] || 0}`)
                            ]) 
                          }) : null
                        ]
                      )
                    }
                  }
                },
                render(h) {
                  return (
                    <test-component />
                  )
                }
              })
              
            })
            return element;
          }
        },
        legend: {
          data: option.legend,
          top: '10px',
          left: '70px'
        },
        grid: {
          left: '20px',
          right: '60px',
          bottom: '20px',
          top: '50px',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: option.title
            }
          },
          right: 40
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            yAxisIndex: [0],
            right: '20px',
            startValue: start,
            endValue: end,
            minValueSpan: 10,
            maxValueSpan: 30
          }
        ],
        yAxis: {
          type: 'category',
          data: option.yAxisData,
          axisLabel: {
            formatter(originText) {
              if (!originText) return '';
              if(originText.length <= 7 || that.isOpenData) {
                return originText
              }
              return `${originText.slice(0, 7)}...`;
            }
          },
        },
        xAxis: {
          type: 'value'
        },
        series: option.series
      };

      if(this.categoryType == t('report.staffCategoryChart.title9') && option.tooltip) {
        _.assign(_option.tooltip, option.tooltip);
      }

      if(option.xAxis) _.assign(_option.xAxis, option.xAxis)

      return _option;
    },
    formatterTime(sec){
      // const DAY_SEC = 60 * 60 * 24;
      const HOUR_SEC = 60 * 60;
      const MIN_SEC = 60;

      // let day = sec / DAY_SEC >> 0;
      // sec = sec % DAY_SEC;

      let hour = sec / HOUR_SEC >> 0;
      sec = sec % HOUR_SEC;

      let min = sec / MIN_SEC >> 0;
      sec = sec % MIN_SEC;

      let temp = '';
      if(hour > 0) temp += `${hour }${t('common.base.hour')}`;
      if(min > 0) temp += `${min }${t('common.base.minute')}`;
      if(sec > 0) temp += `${sec }${t('common.base.second')}`;

      return temp ? temp : '--';
    },
    // 计算最大时间间隔
    computeInterval(sec){
      let interval = {
        min: 0,
        max: null
      }
      
      // 如果时间跨度不大于1小时
      if(sec <= 3600){
        // 以分钟为最小刻度
        interval.min = 60 ;
        // 以10分钟为最大刻度
        interval.max = 60 * 10;
        return interval;
      }

      // 如果时间跨度小于1天
      if(sec <= 3600 * 24){
        // 以小时为最小刻度
        interval.min = 3600;
        return interval;
      }

      // 如果时间跨度大于1天，则按6份划分
      let hour = sec / 3600 >> 0;
      interval.max = (hour / 6 >> 0) * 3600;
      interval.min = 3600;
      return interval
    },
    datePicker(data) {
      // 时间赋值
      this.initDate(data[0], data[1]);
      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TIME', this.$track)
    }
  },
  mounted(){
    this.initCategory();
    window.addEventListener('resize', _.debounce(function(){
      category.resize();
    }, 400))
  },
  watch: {
    categoryType(){
      this.showTable = false;
    }
  },
  components: {
    [BaseCheckbox.name]: BaseCheckbox,
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>

<style lang="scss">
#category{
  height: 100%;
}
.category-chart-wrap{
  width: 100%;
  height: 520px;
  position: relative;
}

.category-chart-empty{
  position: absolute;
  width: 100px;
  text-align: center;
  top: 120px;
  left: 50%;
  margin-left: -50px;
  font-size: 18px;
  font-weight: 500;
  color: #9a9a9a;
}
.stats-staff-category-wrap{
  //padding: 10px;
}
.el-tooltip__popper{
  max-width: 800px;
  word-break: break-all;
}
.statistical-source {
  .el-select {
    width: 120px;
    .el-input>input {
      width: 120px!important;
    }
  }
}
.task-mb2{
  margin-bottom: 2px;
}
</style>

<style lang="scss" scoped>
.stats-form > h3{
  min-width: 120px;
}
</style>